//获取当前激活页ID
function getCurrentTabId(callback){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        if(callback) callback(tabs.length ? tabs[0].id: null);
    });
}

/**
 * 使用链接（dataurl/bloburl）下载文件
 * @param {*} uri  链接
 * @param {*} name 下载文件名称
 */
function downloadURI(uri,name){
    var link = document.createElement("a");
    link.download  = name;
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    delete link;
}

var captureScreenLink = document.getElementById("captureScreenLink");
captureScreenLink.addEventListener("click",function(){
    //绘制整个网页的canvas,canvas的宽高等于网页的宽高
    var fullpageCanvas = document.createElement('canvas');
    getCurrentTabId(function(tabId){
        var scrollTop = 0; //当前滚动条顶部位置
        var scrollLeft = 0; //当前滚动条左侧位置
        chrome.tabs.executeScript(tabId,{
            "code":'document.documentElement.scrollTop'
        },function(output){
            scrollTop = (output && output.length>0)?output[0]:0;
        });
        chrome.tabs.executeScript(tabId,{
            "code":'document.documentElement.scrollLeft'
        },function(output){
            scrollLeft = (output && output.length>0)?output[0]:0;
        });
        chrome.tabs.executeScript(tabId,{
            "code":'document.body.scrollWidth'
        },function(output){
            var width = (output && output.length>0)?output[0]:null;
            fullpageCanvas.width = width;
        });
        chrome.tabs.executeScript(tabId,{
            "code":'document.body.scrollHeight'
        },function(output){
            var height = (output && output.length>0)?output[0]:null;
            fullpageCanvas.height = height;
        });

        var ctx = fullpageCanvas.getContext('2d');
        var capture = function(x,y,finshedFun){
            chrome.tabs.executeScript(tabId,{
                "code":'window.scrollTo('+x+','+y+')'
            },function(){
                chrome.tabs.captureVisibleTab(null,{format:"png"},function(dataUrl){
                    var image = new Image();
                    image.onload=function(){
                        if(fullpageCanvas.width-x<=image.width && fullpageCanvas.height-y<=image.height){
                            //最后一块
                            ctx.drawImage(image,fullpageCanvas.width-image.width,fullpageCanvas.height-image.height);
                            finshedFun(fullpageCanvas.toDataURL("image/png"));

                            //恢复原来位置
                            chrome.tabs.executeScript(tabId,{"code":'window.scrollTo('+scrollLeft+','+scrollTop+')'})
                        }else if(fullpageCanvas.width-x>image.width){
                            //横向还有距离，继续横向
                            ctx.drawImage(image,x,y);
                            x+=image.width;
                            capture(x,y,finshedFun);
                        }else if(fullpageCanvas.width-x<=image.width){
                            //横向完成，纵向走
                            ctx.drawImage(image,fullpageCanvas.width-image.width,y);
                            x = 0;
                            y+=image.height;
                            capture(x,y,finshedFun);
                        }
                    }
                    image.src=dataUrl;
                });
            });
        }

        //从左上角开始截图
        capture(0,0,function(dataUrl){
            var fileName = (new Date()).toISOString()+".png";
            downloadURI(dataUrl,fileName);
        });
    });
});